﻿Imports System.ServiceModel.DomainServices.Client
Imports System.IO

Partial Public Class DocumentAltaModificacio
    Inherits ChildWindow

    Private _Document As Web.Document
    Public ReadOnly Property Document As Web.Document
        Get
            Return _Document
        End Get
    End Property

    Private _Mode As EnumMode
    Public ReadOnly Property Mode As EnumMode
        Get
            Return _Mode
        End Get
    End Property

    Public Enum EnumMode
        ModeAlta
        ModeModificacio
    End Enum

#Region "Crear i Destruir"
    Public Sub New(pMode As EnumMode, pDocument As Web.Document)
        MyBase.New()

        InitializeComponent()
        _Mode = pMode
        _Document = pDocument
    End Sub


    Private Sub Child_Closed(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Closed
        Application.Current.RootVisual.SetValue(Control.IsEnabledProperty, True)
    End Sub

    Private Sub DocumentAlta_Loaded(sender As Object, e As System.Windows.RoutedEventArgs) Handles Me.Loaded
        If RiaContext.Current.Authentication.User.Identity.IsAuthenticated = True Then
            Me.Activity.IsActive = True

            AddHandler Contexte.UsuarisCarregats, AddressOf UsuarisCarregats
            Contexte.LoadUsuaris()

            AddHandler Contexte.HostalsCarregats, AddressOf HostalsCarregats
            Contexte.LoadHostals()

            Dim LListaDates As List(Of OpcioCombo) = (From o As OpcioCombo In OpcionsDatesHoraris.Llista Where DirectCast(o.Objecte, DateTime) > Now.AddMonths(-1)).ToList
            If Mode = EnumMode.ModeModificacio AndAlso Not LListaDates.Contains(Document.DataCombo) Then LListaDates.Insert(0, Document.DataCombo)
            Me.cboData.ItemsSource = LListaDates

            AmagarCamps()

            Me.gridDetall.DataContext = _Document
        End If
    End Sub

    Private Sub AmagarCamps()

        If Not Contexte.UsuariActual.IdTipusUsuari = EnumTipusUsuari.Administrador Then
            cboUsuaris.IsEnabled = False
        End If

        If Contexte.UsuariActual.IdTipusUsuari <> EnumTipusUsuari.Administrador AndAlso Contexte.UsuariActual.IdTipusUsuari <> EnumTipusUsuari.Manager Then
            cboHostals.IsEnabled = False
        End If

        Select Case Mode
            Case EnumMode.ModeAlta
                Me.Title = StringLibrary.AltaDocument

            Case EnumMode.ModeModificacio
                Me.Title = StringLibrary.EditarDocument

        End Select
    End Sub
#End Region

#Region "Carregar Dades"
    Private _HostalsCarregats As Boolean = False
    Private _UsuarisCarregats As Boolean = False

    Private Sub UsuarisCarregats(ByVal Resultat As Boolean, ByVal Missatge As String)
        RemoveHandler Contexte.UsuarisCarregats, AddressOf UsuarisCarregats

        Select Case Mode
            Case EnumMode.ModeAlta
                If Contexte.UsuariActual.IdTipusUsuari = EnumTipusUsuari.Administrador Then
                    cboUsuaris.ItemsSource = (From U As LullabyFullDeCaixa.Web.Usuari In Contexte.Usuaris Where U.IdTipusUsuari <> EnumTipusUsuari.Neteja).ToList
                Else
                    cboUsuaris.ItemsSource = {Contexte.UsuariActual}
                End If

            Case EnumMode.ModeModificacio
                If Contexte.UsuariActual.IdTipusUsuari = EnumTipusUsuari.Administrador Then
                    cboUsuaris.ItemsSource = (From U As LullabyFullDeCaixa.Web.Usuari In Contexte.Usuaris Where U.IdTipusUsuari <> EnumTipusUsuari.Neteja).ToList
                Else
                    cboUsuaris.ItemsSource = {_Document.Usuari}
                End If

        End Select


        _UsuarisCarregats = True
        If _HostalsCarregats And _UsuarisCarregats Then Me.Activity.IsActive = False
    End Sub

    Public Sub HostalsCarregats(ByVal Resultat As Boolean, ByVal Missatge As String)
        RemoveHandler Contexte.HostalsCarregats, AddressOf HostalsCarregats

        Select Case Mode
            Case EnumMode.ModeAlta
                If Contexte.UsuariActual.IdTipusUsuari = EnumTipusUsuari.Administrador Then
                    Me.cboHostals.ItemsSource = Contexte.Hostals
                Else
                    Me.cboHostals.ItemsSource = Contexte.HostalsPerUsuariActual.AsEnumerable
                End If

            Case EnumMode.ModeModificacio
                If Contexte.UsuariActual.IdTipusUsuari = EnumTipusUsuari.Administrador Then
                    Me.cboHostals.ItemsSource = Contexte.Hostals
                Else
                    Me.cboHostals.ItemsSource = {_Document.Hostal}
                End If

            Case Else
                Me.cboHostals.ItemsSource = {_Document.Hostal}

        End Select

        If Me.cboHostals.Items.Count > 0 AndAlso Mode = EnumMode.ModeAlta Then _Document.Hostal = DirectCast(Me.cboHostals.Items(0), Web.Hostal)

        _HostalsCarregats = True
        If _HostalsCarregats And _UsuarisCarregats Then Me.Activity.IsActive = False
    End Sub


#End Region

#Region "Guardar i Cancelar"
    Private Sub OKButton_Click(ByVal sender As Object, ByVal e As RoutedEventArgs)
        EliminarObjectErrors()

        If LullabyFullDeCaixa.Contexte.DomainContext.EntityContainer.HasChanges Then
            If ValidarDades() And Validacio.Errors.Count = 0 Then
                Activity.IsActive = True

                LullabyFullDeCaixa.Contexte.DomainContext.SubmitChanges(AddressOf DomainContext_SubmittedChanges, Nothing)
            End If
        Else
            Me.DialogResult = True
        End If
    End Sub

    Private Function ValidarDades() As Boolean
        Dim Resultat As Boolean = True

        If Document.Usuari Is Nothing Then
            Validacio.Errors.Add(New ValidationSummaryItem(StringLibrary.DebeSeleccionarUnUsuario))
            Resultat = False
        End If

        If Document.Hostal Is Nothing Then
            Validacio.Errors.Add(New ValidationSummaryItem(StringLibrary.DebeSeleccionarUnHostal))
            Resultat = False
        Else
            If (From D As Web.Document In Contexte.DomainContext.Documents Where D IsNot Document AndAlso D.IdHostal = Document.Hostal.Id AndAlso D.DataInicial = Document.DataInicial).Count > 0 Then
                Validacio.Errors.Add(New ValidationSummaryItem(StringLibrary.JaExisteixLhorari))
                Resultat = False
            End If
        End If

        If Mode = EnumMode.ModeAlta AndAlso selectedFile Is Nothing Then
            Validacio.Errors.Add(New ValidationSummaryItem(StringLibrary.ShaDeTriarUnFitxer))
            Resultat = False
        End If

        If selectedFile IsNot Nothing AndAlso selectedFile.Length / 1024 > 500 Then
            Validacio.Errors.Add(New ValidationSummaryItem(StringLibrary.FicherMassaGran))
            Resultat = False
        End If

        If selectedFile IsNot Nothing Then
            Try
                Dim Data As Stream = selectedFile.OpenRead()
                Data.Close()
            Catch ex As Exception
                Validacio.Errors.Add(New ValidationSummaryItem(String.Format(StringLibrary.FicherObert, selectedFile.Name)))
                Resultat = False
            End Try

        End If

        Return Resultat
    End Function

    Private Sub DomainContext_SubmittedChanges(ByVal s As SubmitOperation)
        Activity.IsActive = False

        If s.HasError Then
            App.ReportError(StringLibrary.ErrorGuardantDades)
        Else
            If selectedFile IsNot Nothing Then
                Activity.IsActive = True
                UploadFile()
            Else
                Me.DialogResult = True
            End If
        End If
    End Sub

    Private Sub CancelButton_Click(ByVal sender As Object, ByVal e As RoutedEventArgs)
        If LullabyFullDeCaixa.Contexte.DomainContext.EntityContainer.HasChanges Then
            LullabyFullDeCaixa.Contexte.DomainContext.RejectChanges()
        End If

        Me.DialogResult = False
    End Sub

    Public Sub EliminarObjectErrors()
        Dim i As Long

        i = 0
        While i < Validacio.Errors.Count
            If Validacio.Errors(i).ItemType = ValidationSummaryItemType.ObjectError Then
                Validacio.Errors.RemoveAt(i)
            Else
                i = i + 1
            End If
        End While
    End Sub
#End Region

#Region "Gestió del document"

    Private selectedFile As FileInfo

    Private Sub btSelect_Click(ByVal sender As Object, ByVal e As System.Windows.RoutedEventArgs) Handles btSelect.Click
        Dim dlg As OpenFileDialog = New OpenFileDialog()
        dlg.Multiselect = False

        If dlg.ShowDialog() Then
            Document.FileName = dlg.File.Name
            Document.Mida = dlg.File.Length
            Document.TipusMime = Left(dlg.File.Extension, 5)
            selectedFile = dlg.File
        End If
    End Sub


    Private Sub UploadFile()
        Dim base As String = Application.Current.Host.Source.OriginalString.Replace(Application.Current.Host.Source.AbsolutePath, "")
        Dim ub As New UriBuilder(base + "/Receiver.ashx")
        ub.Query = String.Format("filename={0}&iddoc={1}",
            selectedFile.Name, Document.Id)
        Dim c As New WebClient()
        AddHandler c.OpenWriteCompleted, AddressOf OpenWriteCallback
        c.OpenWriteAsync(ub.Uri)
    End Sub

    Private Sub OpenWriteCallback(ByVal sender As Object, ByVal e As OpenWriteCompletedEventArgs)


        If e.Error IsNot Nothing Then
            App.ReportError(e.Error.Message)
            Activity.IsActive = False
        Else
            Dim Data As Stream = selectedFile.OpenRead()

            PushData(Data, e.Result)
            e.Result.Close()
            Data.Close()

            Activity.IsActive = False
            Me.DialogResult = True
        End If


    End Sub

    Private Sub PushData(ByVal input As Stream, ByVal output As Stream)
        Dim buffer As Byte() = New Byte(4095) {}
        Dim bytesRead As Integer

        bytesRead = input.Read(buffer, 0, buffer.Length)
        While bytesRead <> 0
            output.Write(buffer, 0, bytesRead)
            bytesRead = input.Read(buffer, 0, buffer.Length)
        End While
    End Sub

#End Region

End Class
